//
//  PKHomePageMainViewController.m
//  PianKe
//
//  Created by 王郑 on 16/1/26.
//  Copyright © 2016年 KFC. All rights reserved.
//

#import "PKHomePageMainViewController.h"
#import "DDSoundModel.h"
#import "DDSoundTableViewCell.h"
#import "PKHomeDetailViewController.h"
#import "UIView+Genie.h"
#import "DDCalendarModel.h"
@interface PKHomePageMainViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic,assign)NSInteger requestStart;

@property (nonatomic,strong)NSString *pageid;

@property (nonatomic,strong)NSString *create_time;


// 日历相关 :
@property (strong, nonatomic) UIButton *riliButton;
@property (strong, nonatomic) UIView *draggedView;
@property (nonatomic) BOOL viewIsIn;
@property (nonatomic,strong) NSMutableArray *riLiDataArray;

@end

@implementation PKHomePageMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    _dataArray = [NSMutableArray array];
    _riLiDataArray = [NSMutableArray array];
    _requestStart = 1;
    _pageid = @"0";
    _create_time = @"0";
    
    
    
    
    UIImageView *headImageV = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - 60*kWidthBase)/2, (84 - 30*kHeightBase)/2, 60*kWidthBase, 30*kHeightBase)];
    headImageV.image = [UIImage imageNamed:@"danxiangkongjian"];
    
    [self.view addSubview:headImageV];
    
    

#pragma mark ---- 数据解析
     [self setUpData];
     [self setUpRiLiData];
#pragma mark ---- 添加表视图
    [self addTableView];
    
#pragma mark ---- 日历所在的视图
    _draggedView = [[UIView alloc] initWithFrame:CGRectMake(10*kWidthBase, 64*kHeightBase, kScreenWidth - 20*kWidthBase, kScreenHeight - 84*kHeightBase)];
    _draggedView.backgroundColor = [UIColor whiteColor];
    _draggedView.layer.shadowColor = [[UIColor blackColor]CGColor];
    _draggedView.layer.shadowOffset = CGSizeMake(4,2);
    _draggedView.layer.borderColor = [[UIColor blackColor]CGColor];
    _draggedView.layer.borderWidth = 1;
    // 修改shadow的透明度,不为0就能显示出来
    _draggedView.layer.shadowOpacity = 1;
#pragma mark ---- 日历按钮
    _riliButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _riliButton.frame = CGRectMake(kScreenWidth - 60*kWidthBase, kScreenHeight - 60*kHeightBase, 40*kWidthBase, 40*kHeightBase);
    [_riliButton setBackgroundImage:[UIImage imageNamed:@"iconfont-rili"] forState:(UIControlStateNormal)];
    [_riliButton addTarget:self action:@selector(showRiLi:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_riliButton];
    [self.view bringSubviewToFront:_draggedView];
    [self.view bringSubviewToFront:_riliButton];
    
    
#pragma mark ---- 刷新 , 加载
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        _requestStart = 1;
        _create_time = @"0";
        _pageid = @"0";
        [self setUpData];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        _requestStart += 1 ;
        DDSoundModel *model = _dataArray[_dataArray.count - 1] ;
        _create_time = model.create_time;
        _pageid = model.pageid;
        [self setUpData];
        // 更改start
        
    }];

    
    
}

- (void)setUpData
{
    _str = @"http://static.owspace.com/index.php?m=Home&c=Api&a=getList&model=2&p=1&client=iphone&page_id=0&create_time=0&device_id=B709CBC5-0E2F-4C89-9E24-6AFBBA86C58C&iOS_version=1.0.0";

    NSString *str = [_str stringByReplacingOccurrencesOfString:@"p=1" withString:[NSString stringWithFormat:@"p=%ld",_requestStart]];
    str = [str stringByReplacingOccurrencesOfString:@"page_id=0" withString:[NSString stringWithFormat:@"page_id=%@",_pageid]];
    str = [str stringByReplacingOccurrencesOfString:@"create_time=0" withString:[NSString stringWithFormat:@"create_time=%@",_create_time]];
    [PKRequestManager requestWithUrlString:str parDic:nil Method:GET finish:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        
        NSArray *array = dic[@"datas"];
        if (_requestStart == 1) {
            [_dataArray removeAllObjects];
        }
        for (NSDictionary *oneDic in array) {
            DDSoundModel *model = [[DDSoundModel alloc]init];
            
            [model setValuesForKeysWithDictionary:oneDic];
            
            [self.dataArray addObject:model];
        }
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        [self.tableView reloadData];
        
        
    } error:^(NSError *error) {
        
        
    }];
    
}

- (void)setUpRiLiData
{
    NSString *str0 = @"http://static.owspace.com/index.php?m=Home&c=Api&a=getList&model=4&p=1&client=iphone&page_id=0&create_time=0&device_id=B709CBC5-0E2F-4C89-9E24-6AFBBA86C58C&iOS_version=1.0.0";
    
    NSString *str = [str0 stringByReplacingOccurrencesOfString:@"p=1" withString:[NSString stringWithFormat:@"p=%ld",_requestStart]];
    str = [str stringByReplacingOccurrencesOfString:@"page_id=0" withString:[NSString stringWithFormat:@"page_id=%@",_pageid]];
    str = [str stringByReplacingOccurrencesOfString:@"create_time=0" withString:[NSString stringWithFormat:@"create_time=%@",_create_time]];
    
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
    [request setHTTPMethod:@"get"];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *arr = dic[@"datas"];

        
        if (_requestStart == 1) {
            [_riLiDataArray removeAllObjects];
        }
        for (NSDictionary *one in arr) {
            DDCalendarModel *model = [[DDCalendarModel alloc]init];
            [model setValuesForKeysWithDictionary:one];
            [_riLiDataArray addObject:model];
        }
      
    }];

    

}


- (void)addTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64) style:(UITableViewStylePlain)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 120 * kHeightBase;
    
    [self.view addSubview:self.tableView];
    
    [self.tableView registerClass:[DDSoundTableViewCell class] forCellReuseIdentifier:@"DDSoundTableViewCell"];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DDSoundTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DDSoundTableViewCell" forIndexPath:indexPath];
    
    DDSoundModel *model = self.dataArray[indexPath.row];
    
    cell.model = model;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PKHomeDetailViewController *detailVC = [[PKHomeDetailViewController alloc] init];
    DDSoundModel *model = self.dataArray[indexPath.row];
    detailVC.html5 = model.html5;
    detailVC.pageid = model.pageid;
    detailVC.category = model.category;
    detailVC.titlename = model.title;
    detailVC.thumbnail = model.thumbnail;
    detailVC.author = model.author;
    [self.navigationController pushViewController:detailVC animated:YES];

}

// 展示日历的动画效果
- (void) genieToRect: (CGRect)rect edge: (BCRectEdge) edge
{
    self.viewIsIn = ! self.viewIsIn;
    
    // 第二个 和 第三个 参数是回到箱子里 的内边距 , 不能大于你箱子的宽高
    
    CGRect endRect = CGRectInset(rect, 20.0*kWidthBase, 20.0*kHeightBase);
    
    _riliButton.enabled = NO;
    
    if (_viewIsIn) {
        
        // 从箱子里面出来:
        NSLog(@"从箱子里面出来%d",_viewIsIn);

        if (_riLiDataArray.count != 0) {
            
            DDCalendarModel *model = [_riLiDataArray firstObject];
            UIImageView *riliView = [[UIImageView alloc]init];
            riliView.frame = CGRectMake(0,0, kScreenWidth - 20*kWidthBase, kScreenHeight - 84*kHeightBase);
            [riliView sd_setImageWithURL:[NSURL URLWithString:model.thumbnail] placeholderImage:nil];
            [_draggedView addSubview:riliView];
        }
        
        [self.view addSubview:_draggedView];
        [self.view bringSubviewToFront:_riliButton];
        
        [_draggedView genieOutTransitionWithDuration:1 startRect:endRect startEdge:edge completion:^{
            
            _riliButton.enabled = YES;
        }];
        
        
    }else {
        NSLog(@"进入箱子里面%d",_viewIsIn);
        self.draggedView.userInteractionEnabled = NO;
        
        // 在动画完成后视图的转换将被改变以匹配目标的矩形,即。*视图的转换(因此帧)将会改变,但是范围和中心将*不*变化。
        
        [_draggedView genieInTransitionWithDuration:1 destinationRect:endRect destinationEdge:edge completion:^{
            
            for (UIView *view in [_draggedView subviews]) {
                
                [view removeFromSuperview];
                
            }
            
            _riliButton.enabled = YES;
            
            
        }];
        
        
    }
    
    
    
    
    
}

// 点击日历按钮
- (void)showRiLi:(UIButton *)sender
{
    
    [self genieToRect:sender.frame edge:BCRectEdgeTop];
}


- (void)viewDidUnload
{
    [self setDraggedView:nil];
    
    [super viewDidUnload];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
